<template>
	<view class="chat">
    <view class="topTabbar">
        <view class="topbox">
      		  <view class="title">AI智能导诊</view>
      	  </view>
      <view class="text">匿名</view>
    </view>
		<scroll-view  :style="{height: `${windowHeight-inputHeight - 180}rpx`}"
		id="scrollview"
		scroll-y="true" 
		:scroll-top="scrollTop"
		class="scroll-view"
		>
			<!-- 聊天主体 -->
			<view id="msglistview" class="chat-body">
				<!-- 聊天记录 -->
				<view v-for="(item,index) in msgList" :key="index">
					<!-- 自己发的消息 -->
					<view class="item self" v-if="item.userContent != ''" >
						<!-- 文字内容 -->
						<view class="content right">
						{{item.userContent}}
						</view>
						<!-- 头像 -->
						<image class="avatar" :src="item.image">
						</image>
					</view>
					<!-- 机器人发的消息 -->
					<view class="item Ai" v-if="item.botContent != ''">   
						<image class="avatar" :src="item.image">
						</image>
						<view class="content left">
							{{item.botContent}}
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<!-- 底部消息发送栏 -->
		<view class="chat-bottom" :style="{height: `${inputHeight}rpx`}">
			<view class="send-msg" :style="{bottom:`${keyboardHeight - 60}rpx`}">
        <view class="uni-textarea">
		<view class="startVoiceRecognition">
				<view :class="['mic-layer',{'mic-layer-talking':isTalking}]">
					<!-- 按钮样式 -->
					<view :class="isTalking?'mic-btn-talking':'mic-btn'" @touchstart="touchStart" @touchend="onEnd" @longpress="onStart" @touchmove="handleRecordMove">
						<view v-show="!isTalking" class="record-button">
							<text class="">语音</text>
						</view>
						<view v-show="isTalking" class="mic-btn-talking_text">说话中...</view>
						<view v-show="isTalking&&!sendLock" class="tip-text"><text class="mr-10">松开</text>发送</view>
					</view>
					<!-- 语音音阶动画 -->
					<view v-if="isTalking" :class="['record-animate-box',{'active':sendLock}]">
						<view class="voice-scale">
							<view class="item" v-for="(item,index) in 10" :key="index"></view>
						</view>
					</view>
					<!-- 取消发送 -->
					<view v-if="isTalking":class="['record-cancel',{'active':sendLock}]">
						<!-- ⬇️可换成自己的icon -->
						<text class="close-icon">x</text>
						<!-- ⬆️️可换成自己的icon -->
						<view class="tip-text" v-show="sendLock"><text class="mr-10">松开</text>取消</view>
					</view>
				</view>
			</view>
          <textarea v-model="chatMsg"
            maxlength="300"
            confirm-type="send"
            @confirm="handleSend"
            placeholder="快来聊天吧~"
            :show-confirm-bar="false"
            :adjust-position="false"
            @linechange="sendHeight"
            @focus="focus" @blur="blur"
           auto-height></textarea>
        </view>
				<button @click="handleSend" class="send-btn">发送</button>
			</view>
		</view>
	</view>
</template>
<script>
	export default{
		data() {
			return {
				isTalking: false, // 是否正在讲话
				sendLock: false, // 语音是否发送锁，true-不发送，false-发送（用于上滑取消发送）
				record: null, // 语音对象
				startPoint: {}, //记录长按录音开始点信息,用于后面计算滑动距离。
				keyboardHeight:0,
				bottomHeight: 0,
				scrollTop: 0,
				userId:'',
				chatMsg:"",
				msgList:[
					{
					    botContent: "hi~我是AI问病助手暖暖，你有任何需要都可以向我提问，我一直都在哦~",
					    userContent: "",
              image:"/static/黄.png"
					},
					{
					    botContent: "",
					    userContent: "你好呀，非常高兴认识你",
              image:"/static/common/unname2.jpg"
					},
				]	
			}
		},
		updated(){
			this.scrollToBottom();
		},
		computed: {
			windowHeight() {
			    return this.rpxTopx(uni.getSystemInfoSync().windowHeight)
			},
			inputHeight(){
				return this.bottomHeight+this.keyboardHeight
			}
		},
		onLoad(){
        uni.onKeyboardHeightChange(res => {
				this.keyboardHeight = this.rpxTopx(res.height)
				if(this.keyboardHeight<0)this.keyboardHeight = 0;
			})
		},
		onUnload(){
		},
		methods: {
	/**
				 * 开始录音
				 */
				onStart() {
					const option = {
						format: 'mp3'
					}
					console.log('start');
					this.isTalking = true
					uni.vibrateShort(); // 震动
					this.record.start(option)
					this.record.onStart(res => {
						console.log('start',res);
					})
					this.record.onError(res => {
						console.log('录音错误事件：',res);
					})
				},
				/**
				 * 结束录音
				 */
				onEnd() {
					this.isTalking = false
					this.record.stop()
					this.record.onStop(res => {
						console.log(res, "录音回调地址");
						if(this.sendLock){
							this.sendLock = false // 恢复锁状态
							console.log('取消发送');
							return
						} // 取消发送
						if (res.duration < 1000) {
							uni.showToast({
								icon: 'error',
								title: '说话时间太短'
							})
							return
						}
						// TODO
						// ***
					})
				},
				/**
				 * 开始触屏
				 * @param {Object} e
				 */
				touchStart(e){
					this.startPoint.clientX = e.changedTouches[0].clientX; //手指按下时的X坐标
					this.startPoint.clientY = e.changedTouches[0].clientY; //手指按下时的Y坐标
				},
				/**
				 * 录音时手指滑动
				 * @param {Object} e
				 */
				handleRecordMove(e){
					let touchData = e.touches[0]; //滑动过程中，手指滑动的坐标信息
					let moveX = touchData.clientX - this.startPoint.clientX;
					let moveY = touchData.clientY - this.startPoint.clientY;
					if(moveY > -45){ // 滑动距离不够则不取消发送
						this.sendLock = false
					} else {
						this.sendLock = true
					}
				},
			
			onLoad() {	
				this.record = uni.getRecorderManager()
			},
      goback() {
        uni.switchTab({
          url: "/pages/tutorship/tutorship"
        })
      },
			focus(){
				this.scrollToBottom()
			},
			blur(){
				this.scrollToBottom()
			},
			rpxTopx(px){
				let deviceWidth = uni.getSystemInfoSync().windowWidth
				let rpx = ( 750 / deviceWidth ) * Number(px)
				return Math.floor(rpx)
			},
			sendHeight(){
				setTimeout(()=>{
					let query = uni.createSelectorQuery();
					query.select('.send-msg').boundingClientRect()
					query.exec(res =>{
						this.bottomHeight = this.rpxTopx(res[0].height)
					})
				},10)
			},
			// 滚动至聊天底部
			scrollToBottom(e){
				setTimeout(()=>{
					let query = uni.createSelectorQuery().in(this);
					query.select('#scrollview').boundingClientRect();
					query.select('#msglistview').boundingClientRect();
					query.exec((res) =>{
						if(res[1].height > res[0].height){
							this.scrollTop = this.rpxTopx(res[1].height - res[0].height)
						}
					})
				},15)
			},
			// 发送消息
			handleSend() {
				if(!this.chatMsg||!/^\s+$/.test(this.chatMsg)){
					let obj = {
						botContent: "",
						userContent: this.chatMsg,
            image:"/static/common/unname2.jpg"
					}
					this.msgList.push(obj);
					this.chatMsg = '';
					this.scrollToBottom()
				}else {
					this.$modal.showToast('不能发送空白消息')
				}
			},
		}
	}
</script>
<style lang="scss" scoped>
	
	$chatContentbgc: #C2DCFF;
	$sendBtnbgc: #4F7DF5;
	.topbox{
			.title{
				position: absolute;
				left: 98px;
				top: 16px;
				width: 190px;
				height: 63px;
				opacity: 1;
				
				font-family: Source Han Sans;
				font-size: 36px;
				font-weight: normal;
				line-height: normal;
				letter-spacing: 0em;
				
				font-variation-settings: "opsz" auto;
				font-feature-settings: "kern" on;
				color: #0256FF;
			}
			position: absolute;
			left: 0px;
			top: 0px;
			width: 375px;
			height: 95px;
			opacity: 1;
			
			background: #E0EAFF;
			
		}
		

	view,button,text,input,textarea {
		margin: 0;
		padding: 0;
		box-sizing: border-box;
	}
 
	/* 聊天消息 */
	.chat {
     .topTabbar {
          width: 100%;
          height: 90rpx;
          line-height: 90rpx;
          display: flex;
          margin-top: 80rpx;
          justify-content: space-between;
      
          .icon {
            margin-left: 20rpx;
          }
      
          .text {
            margin: auto;
            font-size: 16px;
            font-weight: 700;
          }
      
          .button {
            width: 10%;
            margin: auto 20rpx auto 0rpx;
          }
        }
		.scroll-view {
			::-webkit-scrollbar {
					    display: none;
					    width: 0 !important;
					    height: 0 !important;
					    -webkit-appearance: none;
					    background: transparent;
					    color: transparent;
					  }
			
			background-color: #F6F6F6;
			
			.chat-body {
				display: flex;
				flex-direction: column;
				padding-top: 23rpx;
				// background-color:skyblue;
				
				.self {
					justify-content: flex-end;
				}
				.item {
					display: flex;
					padding: 23rpx 30rpx;
					// background-color: greenyellow;
 
					.right {
						background-color: $chatContentbgc;
					}
					.left {
						background-color: #FFFFFF;
					}
                    // 聊天消息的三角形
					.right::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						left: 100%;
						top: 10px;
						border: 12rpx solid transparent;
						border-left: 12rpx solid $chatContentbgc;
					}
 
					.left::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						top: 10px;
						right: 100%;
						border: 12rpx solid transparent;
						border-right: 12rpx solid #FFFFFF;
					}
 
					.content {
						position: relative;
						max-width: 486rpx;
						border-radius: 8rpx;
						word-wrap: break-word;
						padding: 24rpx 24rpx;
						margin: 0 24rpx;
						border-radius: 5px;
						font-size: 32rpx;
						font-family: PingFang SC;
						font-weight: 500;
						color: #333333;
						line-height: 42rpx;
					}
 
					.avatar {
						display: flex;
						justify-content: center;
						width: 78rpx;
						height: 78rpx;
						background: $sendBtnbgc;
						border-radius: 50rpx;
						overflow: hidden;
						
						image {
							align-self: center;
						}
 
					}
				}
			}
		}
 
		/* 底部聊天发送栏 */
		.chat-bottom {
		  width: 100%;
		  height: 100rpx;
		  background: #F4F5F7;
		  transition: all 0.1s ease;
		
		 .send-msg {
		   display: flex;
		   align-items: center; /* 垂直居中 */
		   padding: 16rpx 30rpx;
		   width: 100%;
		   min-height: 177rpx;
		   position: fixed;
		   bottom: 0;
		   background: #fff;
		   transition: all 0.1s ease;
		
		    .uni-textarea {
		      padding-bottom: 100rpx;
		      textarea {
		        width: 537rpx;
				left:60rpx;
		        min-height: 75rpx;
		        max-height: 500rpx;
		        background: #f1f1f1;
		        border-radius: 40rpx;
		        font-size: 32rpx;
		        font-family: PingFang SC;
		        color: #333333;
		        line-height: 74rpx;
		        padding: 5rpx 8rpx;
		        text-indent: 30rpx;
		      }
		    }
		
		    .send-btn {
		      display: flex;
		      align-items: center;
		      justify-content: center;
		      margin-bottom: 100rpx;
		      margin-left: 80rpx;
		      width: 120rpx;
		      height: 75rpx;
		      background: #1373E9;
		      border-radius: 50rpx;
		      font-size: 28rpx;
		      font-family: PingFang SC;
		      font-weight: 500;
		      color: #FFFFFF;
		      line-height: 28rpx;
		    }
		  }
		}
		 }
		.mr-10 {
		  margin-right: 10rpx;
		}
		
		.mic-layer {
		  width: 85rpx; /* 设置按钮宽度 */
		  height: 75rpx; /* 设置按钮高度 */
		  margin-left: -10px; /* 设置语音按钮与文本域的间距 */
		  position: fixed;
		  margin-bottom: 40rpx;
		  bottom: 30rpx;
		  width: 100%;
		  box-sizing: border-box;
		  .record-button {
		    width: 80rpx; 
		    border-radius: 50rpx; 
		    background-color: #2878F4;
		    color: #FFFFFF;
		    height: 80rpx;
		    line-height: 80rpx;
		    text-align: center;
		  }
		}

		 /* 讲话中样式 */
		 	.mic-layer-talking{
		 		position: fixed;
		 		width: 100vw;
		 		height: 100vh;
		 		left: 0;
		 		top: 0;
		 		background-color: rgba(0, 0, 0, .6);
		 		.mic-btn-talking{
		 			position: absolute;
		 			bottom: 0;
		 			width: 100vw;
		 			height: 200rpx;
		 			border-radius: 80px 80px 0 0;
		 			background-color: #F2F2F2;
		 			&_text{
		 				color: #999999;
		 				padding: 60rpx 0;
		 				text-align: center;
		 			}
		 		}
		/* 发送、取消提示文字 */
				.tip-text{
					position: absolute;
					top: -60rpx;
					left: 50%;
					width: 160rpx;
					text-align: center;
					transform: translateX(-50%);
					color: #E3E4EA;
					font-size: 24rpx;
				}
		/* 上方语音动画 */
				.record-animate-box{
					position: absolute;
					left: 50%;
					top: 50%;
					transform: translate(-50%,-50%);
					width: 300rpx;
					height: 140rpx;
					background-color: #2878F4;
					border-radius: 28rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					transition: all .3s;
					&.active{
						background-color: #f56c6c;
						width: 140rpx;
					}}
		/* 语音音阶 */
					.voice-scale {
						width: 60%;
						height: 40rpx;
						display: flex;
						align-items: center;
						justify-content: space-between;
						.item {
							display: block;
							background: #333333;
							width: 4rpx;
							height: 10%;
							margin-right: 2.5px;
							float: left;
							&:last-child{
								margin-right: 0px;
							}
							&:nth-child(1) {
								animation: load 1s 0.8s infinite linear;
							}
						
							&:nth-child(2) {
								animation: load 1s 0.6s infinite linear;
							}
						
							&:nth-child(3) {
								animation: load 1s 0.4s infinite linear;
							}
						
							&:nth-child(4) {
								animation: load 1s 0.2s infinite linear;
							}
						
							&:nth-child(5) {
								animation: load 1s 0s infinite linear;
							}
						
							&:nth-child(6) {
								animation: load 1s 0.2s infinite linear;
							}
						
							&:nth-child(7) {
								animation: load 1s 0.4s infinite linear;
							}
						
							&:nth-child(8) {
								animation: load 1s 0.6s infinite linear;
							}
						
							&:nth-child(9) {
								animation: load 1s 0.8s infinite linear;
							}
						
							&:nth-child(10) {
								animation: load 1s 1s infinite linear;
							}
						}
					}
	@keyframes load {
					0% {
						height: 10%;
					}
			
					50% {
						height: 100%;
					}
			
					100% {
						height: 10%;
					}
				}
			/* 取消按钮 */
					.record-cancel{
						position: absolute;
						left: 50%;
						bottom: 300rpx;
						transform: translateX(-50%);
						width: 100rpx;
						height: 100rpx;
						border-radius: 50%;
						background-color: rgba(0, 0, 0, .2);
						display: flex;
						justify-content: center;
						align-items: center;
						transition: all .3s;
						&.active{
							transform: translateX(-50%) scale(1.2);
							background-color: #f56c6c;
						}
						.close-icon{
							font-size: 40rpx;
							color: #FFFFFF;
						}
					}
		  }
</style>